package core;

import java.util.HashMap;
import java.util.Map;

/**
 * Represents a set of mappings between <code>GameObject</code>s and ids (and
 * vice-versa). There is one <code>Dictionary</code> per game, which is shared
 * between different <code>ObjectStoringStrategies</code>.
 */
public class Dictionary
{
	public void update(Game game) {
		Map<Integer, GameObject> newIdToObjMap = new HashMap<Integer, GameObject>();
		Map<GameObject, Integer> newObjToIdMap = new HashMap<GameObject, Integer>();
		addRecursively(game, newObjToIdMap, newIdToObjMap);
		idToObjMap = newIdToObjMap;
		objToIdMap = newObjToIdMap;
	}

	private void addRecursively(GameObject object, Map<GameObject, Integer> newObjToIdMap, Map<Integer, GameObject> newIdToObjMap) {
		Integer id = objToIdMap.containsKey(object) ? objToIdMap.get(object) : ++lastId;
		newObjToIdMap.put(object, id);
		newIdToObjMap.put(id, object);
		for (java.util.Collection<? extends GameObject> children : object.getChildrens())
			for (GameObject child : children)
				addRecursively(child, newObjToIdMap, newIdToObjMap);
	}

	public GameObject getObject(Integer id) {
		return idToObjMap.get(id);
	}

	public Integer getId(GameObject object) {
		return objToIdMap.get(object);
	}

	private Map<GameObject, Integer> objToIdMap = new HashMap<GameObject, Integer>();
	private Map<Integer, GameObject> idToObjMap = new HashMap<Integer, GameObject>();
	private Integer lastId = 0;
}